import tkinter as tk
import pyperclip
import re

def process_text(text):
    """
    处理剪贴板中的字幕文本，过滤序号、时间戳和空行。
    """
    lines = text.splitlines()
    filtered = []
    
    # 正则表达式模式匹配时间戳
    timestamp_pattern = re.compile(r'^\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}$')
    
    for line in lines:
        stripped_line = line.strip()
        if re.match(r'^\d+', stripped_line):  # 过滤序号行
            continue
        elif timestamp_pattern.match(stripped_line):  # 过滤时间戳行
            continue
        elif re.match(r'^\s*$', stripped_line):  # 过滤空行
            continue
        else:
            filtered.append(line)

    return '\n'.join(filtered)

def check_clipboard():
    """
    持续监视剪贴板内容，检测到变化后自动处理。
    """
    global last_processed
    try:
        current_text = pyperclip.paste()
        if current_text != last_processed:
            processed_text = process_text(current_text)
            pyperclip.copy(processed_text)  # 无条件更新剪贴板
            status_label.config(text="✅ 检测到剪贴板变化并已处理", fg="green")
            last_processed = processed_text
    except Exception as e:
        status_label.config(text=f"❌ 处理失败: {str(e)}", fg="red")
    
    # 每隔1秒检查一次剪贴板
    root.after(1000, check_clipboard)

# 创建主窗口
root = tk.Tk()
root.title("字幕文本清理器")
root.geometry("400x200")
root.resizable(False, False)

# 状态标签
status_label = tk.Label(
    root,
    text="监视剪贴板中...",
    font=("Arial", 12),
    wraplength=300,
    justify="center",
    fg="gray"
)
status_label.pack(pady=30)

# 初始化剪贴板状态变量
last_processed = None

# 启动剪贴板监视
check_clipboard()

# 启动主循环
root.mainloop()